/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "Component.h"
#include "GameObject.h"
#include "PQException.h"

namespace PQEngine
{
	//safe method convert object type to component type
	ComponentType convertComponentType(ObjectType type)
	{
		switch(type){
		case OBJECT_TYPE_COMPONENT_TRANSFORM:
			return COMPONENT_TYPE_TRANSFORM;
		case OBJECT_TYPE_COMPONENT_MESH:
			return COMPONENT_TYPE_MESH;
		case OBJECT_TYPE_COMPONENT_RIGIDBODY:
			return COMPONENT_TYPE_RIGIDBODY;
		case OBJECT_TYPE_COMPONENT_TERRAIN:
			return COMPONENT_TYPE_TERRAIN;
		case OBJECT_TYPE_COMPONENT_LIGHT:
			return COMPONENT_TYPE_LIGHT;
		case OBJECT_TYPE_COMPONENT_PLANE_COLLIDER:
		case OBJECT_TYPE_COMPONENT_BOX_COLLIDER:
		case OBJECT_TYPE_COMPONENT_SPHERE_COLLIDER:
		case OBJECT_TYPE_COMPONENT_CYLINDER_COLLIDER:
		case OBJECT_TYPE_COMPONENT_CONE_COLLIDER:
		case OBJECT_TYPE_COMPONENT_CAPSULE_COLLIDER:
		case OBJECT_TYPE_COMPONENT_CONVEX_HULL_COLLIDER:
			return COMPONENT_TYPE_COLLIDER;
		//case OBJECT_TYPE_COMPONENT_SCRIPT:
			//return COMPONENT_TYPE_SCRIPT;
		
		}
		
		return COMPONENT_TYPE_UNKOWN;
	}

	Component::Component(ObjectType type)
		: Object(type),_componentType(COMPONENT_TYPE_UNKOWN)
	{
		_object=NULL;
		_componentType=convertComponentType(type);
		if(_componentType==COMPONENT_TYPE_UNKOWN){
			PQThrowShouldNotReach();
		}

		//this->created();
	}

	Component::~Component()
	{
		//this->deleted();
	}

	void Component::update(float deltaT)
	{
	}

	//must create new component before attach
	void Component::attach(GameObject *obj)
	{
		_object=obj;
		obj->addComponent(this);

		Event* evt=new Event(Event::EVENT_COMPONENT_ATTACHED,this);
		this->dispatchEvent(evt);
		delete evt;
	}

	void Component::detach()
	{
		_object->removeComponent(this);
		_object=NULL;

		Event* evt=new Event(Event::EVENT_COMPONENT_DETACHED,this);
		this->dispatchEvent(evt);
		delete evt;
	}

	void Component::updateProperty()
	{
		Event* evt=new Event(Event::EVENT_COMPONENT_PROPERTY_UPDATED,this);
		this->dispatchEvent(evt);
		delete evt;
	}

}
